package com.fmh.mybatisplus.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Jwt工具类
 */

@Data
@Component
@ConfigurationProperties(prefix = "fmh.jwt")
public class JwtUtil {

    private long stale; // 过期时间
    private String secret; // 秘钥
    private String header; // jwt名称

    //生成 jwt
    public String generateToken(String username) {
        Date nowDate = new Date(); //生成时间
        Date expireDate = new Date(nowDate.getTime() + 1000 * stale);  //7天时间

         return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();

    }


    //解析 jwt
    public  Claims getClaimsGetToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        }   catch (Exception e) {
            return null;
        }
    }

    // jwt是否过期
    public boolean isTokenExpired(Claims claims) {
        // 判断时间是否大于当前之前
        return claims.getExpiration().before(new Date());
    }
}
